#! /bin/sh

# when building on cygwin
if [ "$1" != win ] ; then export gic="-input-charset utf8" ; fi

# various exports
export PREFIX=~/hobby-os
export PATH=/usr/cross/bin:$PATH
export ARCH=x86
export INCLUDES="-I. -I$PREFIX/include -I$PREFIX/arch/$ARCH/include"
export DEFINES="-DDEBUG"
export ASFLAGS="-f elf $DEFINES -i$PREFIX/obj/kernel/" # we use an 'incbin' directive in nasm to include the kernel here.
export CFLAGS="-c $INCLUDES $DEFINES -ffreestanding -fno-builtin"
export CC=i586-elf-gcc
export LD=i586-elf-ld
export AS=nasm

# make some object directories
cd $PREFIX
if [ ! -e ./obj ] ; then mkdir obj; fi
cd obj
if [ ! -e ./boot ] ; then mkdir boot; fi
cd ..

#build the kernel
touch $PREFIX/obj/kernel/kernel

# build the kernel stub
export BOOTOBJ=$PREFIX/obj/boot
cd $PREFIX/arch/$ARCH/boot
if [ $ARCH = x86 ] ; then
  $AS $ASFLAGS -o $BOOTOBJ/head.o head.s
  $CC $CFLAGS -o $BOOTOBJ/multiboot.o multiboot.c
  $CC $CFLAGS -o $BOOTOBJ/video.o video.c
  $CC $CFLAGS -o $BOOTOBJ/misc.o misc.c
fi
cd $BOOTOBJ
$LD -T $PREFIX/arch/$ARCH/boot/linker.ld -o /media/myos/boot/myos head.o multiboot.o video.o misc.o

# copy the kernel
cd $PREFIX
cp /media/myos/boot/myos ./isofiles/boot/myos

# create and copy initrd (a .tgz file)
cd initrdfiles
tar -czf /media/myos/boot/initrd.gz *
cd ..
cp /media/myos/boot/initrd.gz ./isofiles/boot/initrd.gz

# make an iso image for testing
genisoimage -R -b boot/grub/stage2_eltorito -no-emul-boot -boot-load-size 4 $gic -boot-info-table -quiet -o myos.iso isofiles
